package sword.T32;

import util.TreeNode;

import java.util.*;

/**
 * @Author: 18362
 * @Create: 2022-04-10 21:36:21 星期日
 */
class Solution3 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null)
            return result;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int time = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> arr = new ArrayList<>(size);
            for (int i=0; i<size; ++i) {
                TreeNode front = queue.poll();
                arr.add(front.val);
                if (front.left != null)
                    queue.offer(front.left);
                if (front.right != null)
                    queue.offer(front.right);
            }
            if ((time & 1) != 0)
                Collections.reverse(arr);
            result.add(arr);
            time++;
        }
        return result;
    }
}
